package com.zcl.IO.randomAccessFile;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/15  16:03
 * RandomAccessFile的使用:
 * 1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
 * 2.RandomAccessFile即可以作为一个输入流,也可以作为输出流
 * 3.如果RandomAccessFile作为输出流,写出到文件如果不存在,则执行过程中自动创建
 *      如果写出文件已经存在,则会对原有的文件内容进行覆盖(原文件内容:"qwertyui",写出内容:"123",覆盖后文件:"123rtyui")
 *
 */
public class RandomAccessFileTest {

    @Test
    public void test1() {
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("src\\com\\zcl\\IO\\randomAccessFile\\p1.jpg"), "r");
            raf2 = new RandomAccessFile(new File("src\\com\\zcl\\IO\\randomAccessFile\\p2.jpg"), "rw");

            byte[] bytes = new byte[1024];
            int len;
            while ((len = raf1.read(bytes)) != -1) {
//                raf2.seek(3);//调整光标位置,写入文件的光标索引
                raf2.write(bytes, 0, len);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (raf1 != null) {
                try {
                    raf1.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (raf2 != null) {
                try {
                    raf2.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() throws IOException {
        Path path = Paths.get("src\\com\\zcl\\IO\\randomAccessFile\\p1.jpg");
        InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ);


    }
}
